package gdal_grid;

import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconstConstants;
import org.gdal.ogr.DataSource;
import org.gdal.gdal.Driver;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
import org.gdal.osr.SpatialReference;
import utils.SelectFile;

import java.util.Vector;

import static org.gdal.gdalconst.gdalconstConstants.GDT_Float32;

public class Vectot2Raster {
    public static void main(String[] args) {
        String pathShape = "E:\\TestInput\\vector\\forestdata.shp";
        String pathTif = "E:\\Test\\WaterResources_Clip.tif";

        vector2R(pathShape, pathTif, 30, "DI_LEI");
    }

    /**
     * 矢量转栅格
     * @param pathShape 输入
     * @param pathTif 输出
     * @param accuracy 转换精度（30,120,300）
     * @param field 转换字段
     */
    public static void vector2R(String pathShape, String pathTif, double accuracy, String field) {
        org.gdal.ogr.Driver driver = SelectFile.driverInit();
        double sAc = accuracy / 111000;

        DataSource dataSource = driver.Open(pathShape, 1);
        System.out.println("" + dataSource);

        Layer layer = dataSource.GetLayer(0);
        double[] extent = layer.GetExtent();

        for(double d : extent) {
            System.out.println("d = " + d);
        }
        int imageWidth = (int) ((extent[1] - extent[0])/ sAc);
        int imageHeight = (int) ((extent[3] - extent[2])/ sAc);

        SpatialReference spatialReference = layer.GetSpatialRef();
        String devStr = "GTiff";
        Driver driverTif = gdal.GetDriverByName(devStr);

        Dataset dataset = driverTif.Create(pathTif,imageWidth, imageHeight,1, gdalconstConstants.GDT_Byte);
        System.out.println(dataset);

        double[] adfGeoTransform = new double[6];
        adfGeoTransform[0] = extent[0];
        adfGeoTransform[1] = sAc;
        adfGeoTransform[2] = 0;
        adfGeoTransform[3] = extent[2];
        adfGeoTransform[4] = 0;
        adfGeoTransform[5] = sAc;
        dataset.SetGeoTransform(adfGeoTransform);
        dataset.SetSpatialRef(spatialReference);

        Vector<String> vector = new Vector<String>();
        vector.add("ATTRIBUTE="+field);

        int[] pnbandlist = new int[]{1};
        double[] dburnValues = new double[]{255};

        gdal.RasterizeLayer(dataset,pnbandlist,layer,dburnValues, vector);
    }
}
